package com.huxiu.pagers;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.huxiu.APP;
import com.huxiu.BaseActivity;
import com.huxiu.FanKuiActivity;
import com.huxiu.LogInActivity;
import com.huxiu.MainActivity;
import com.huxiu.MessageActivity;
import com.huxiu.MyCommentActivity;
import com.huxiu.R;
import com.huxiu.SettingActivity;
import com.huxiu.ShouCangActivity;
import com.huxiu.base.BasePager;
import com.huxiu.net.GsonRequest;
import com.huxiu.net.NetworkConstants;
import com.huxiu.net.model.User;
import com.huxiu.net.responses.ProfileResponse;
import com.huxiu.utils.Constants;

import com.huxiu.utils.Global;

import com.huxiu.utils.ImageLoaderOptions;
import com.huxiu.utils.LogUtil;
import com.huxiu.utils.Settings;
import com.huxiu.utils.UmenEvent;
import com.huxiu.utils.Utils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.exception.WeiboException;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.util.LinkedHashMap;
import java.util.Map;


public class MyPager extends BasePager implements OnClickListener {

    private View view;

    //未登录
    @ViewInject(R.id.mine_no_text)
    private TextView mineTiShi;
    @ViewInject(R.id.mine_no_tubiao)
    private LinearLayout mineNoDengLu;

    @ViewInject(R.id.denglu_huxiu)
    private ImageView dengluHuXiu;
    @ViewInject(R.id.denglu_qq)
    private ImageView dengluQQ;
    @ViewInject(R.id.denglu_sina)
    private ImageView dengluSina;
    @ViewInject(R.id.denglu_weixin)
    private ImageView dengluWeiXin;

    //登录成功
    @ViewInject(R.id.mine_ok)
    private LinearLayout mineOK;
    @ViewInject(R.id.mine_ok_touxiang)
    private ImageView mineOkTouXiang;
    @ViewInject(R.id.dengji)
    private ImageView dengji;
    @ViewInject(R.id.mine_ok_name)
    private TextView name;
    @ViewInject(R.id.mine_ok_jianjie)
    private TextView jianjie;


    //每个条目
    @ViewInject(R.id.mine_xiaoxi)
    private LinearLayout mineXiaoxi;
    @ViewInject(R.id.hongdian)
    private ImageView hongdian;//我的消息红点提示


    //    @ViewInject(R.id.mine_wenzhang)
    //    private LinearLayout mineWenzhang;
    @ViewInject(R.id.mine_pinglun)
    private LinearLayout minePinglun;
    @ViewInject(R.id.mine_shoucang)
    private LinearLayout mineShoucang;
    @ViewInject(R.id.mine_setting)
    private LinearLayout mineSetting;
    @ViewInject(R.id.mine_fankui)
    private LinearLayout mineFankui;
    @ViewInject(R.id.layout_shoucang)
    private LinearLayout layout_shoucang;
    @ViewInject(R.id.view_line)
    private View view_line;

    private User user;

    @Override

    protected View init() {
        view = View.inflate(mContext, R.layout.mine, null);
        ViewUtils.inject(this, view);
        if (!Settings.isLoggedIn()) {
            hideUi();
        } else {
            if (Global.user != null) {
                user = Global.user;
                showUi();
            }
        }
        mineXiaoxi.setOnClickListener(this);
        //        mineWenzhang.setOnClickListener(this);
        minePinglun.setOnClickListener(this);
        mineShoucang.setOnClickListener(this);
        mineSetting.setOnClickListener(this);
        mineFankui.setOnClickListener(this);
        dengluHuXiu.setOnClickListener(this);
        mineTiShi.setOnClickListener(this);
        dengluQQ.setOnClickListener(this);
        dengluSina.setOnClickListener(this);
        dengluWeiXin.setOnClickListener(this);
        return view;
    }

    public MyPager(Context context) {
        super(context);

    }

    @Override
    public void initData() {
        //注册广播接收者，并添加多个过滤器
        IntentFilter intent = new IntentFilter();
        intent.addAction(Constants.INTENT_USER_LOGGED_OUT);
        intent.addAction(Constants.INTENT_USER_LOGGED_IN);
        LocalBroadcastManager.getInstance(APP.getInstance()).registerReceiver(mReceiver, intent);
    }


    public static void checkBinQQ(final String token, final String openId, final int typeId) {
        String url = NetworkConstants.OAUTH_LOGIN_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("oauth_uid", openId);
        params.put("oauth_token", token);
        switch (typeId) {
            case Constants.LOGIN_TYPE_QQID:
                params.put("oauth_type", "qq");
                break;
            case Constants.LOGIN_TYPE_SINAID:
                params.put("oauth_type", "sina");
                break;
            case Constants.LOGIN_TYPE_WXID:
                params.put("oauth_type", "weixin");
                break;
        }

        GsonRequest<ProfileResponse> request = new GsonRequest<>(url, Request.Method.POST,
                ProfileResponse.class, true, params, new Response.Listener<ProfileResponse>() {
            @Override
            public void onResponse(ProfileResponse response) {
                if (response.isSuccess()) {
                    Intent intent = new Intent(Constants.INTENT_USER_LOGGED_IN);
                    Gson gson = new Gson();
                    String json = gson.toJson(response.data);
                    intent.putExtra("loginJson", json);
                    LocalBroadcastManager.getInstance(APP.getInstance()).sendBroadcast(intent);
                    Utils.showToast("登录成功");
                } else {
                    //                    Utils.showToast(response.error.message);
                    bindZhuCe(typeId, token, openId);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //                Utils.showToast(error.getMessage());
                bindZhuCe(typeId, token, openId);
            }
        });
        BaseActivity.getmQueue().add(request);
        //        NetworkHelper.getInstance().addToRequestQueue(request);
    }

    //qq跳转到注册绑定的界面
    public static void bindZhuCe(int typeID, String token, String openId) {
        Intent intent = new Intent(mContext, LogInActivity.class);
        intent.putExtra("disanfang", "sanfangguanlian");
        intent.putExtra("tokenStr", token);
        intent.putExtra("openIdStr", openId);
        intent.putExtra("type_id", typeID);
        mContext.startActivity(intent);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.denglu_huxiu:
            case R.id.mine_no_text:
                UmenEvent.UmengEventMap(mContext, UmenEvent.APP_USERCENTER, UmenEvent.USERCENTER_LOGIN_ACCOUNT);
                Intent intent = new Intent(mContext, LogInActivity.class);
                mContext.startActivity(intent);
                break;
            case R.id.denglu_qq:
                UmenEvent.UmengEventMap(mContext, UmenEvent.APP_USERCENTER, UmenEvent.ACCOUNT_LOGIN_QQ);
                //qq第三方登录
                Tencent.createInstance(Constants.TENCENT_APP_ID,
                        mContext).login((Activity) mContext, "all", new
                        listenerQQ());
                break;
            case R.id.denglu_sina:
                UmenEvent.UmengEventMap(mContext, UmenEvent.APP_USERCENTER, UmenEvent.ACCOUNT_LOGIN_WEIBO);
                MainActivity.mSsoHandler.authorize(new AuthListener());
                break;
            case R.id.denglu_weixin:
                UmenEvent.UmengEventMap(mContext, UmenEvent.APP_USERCENTER, UmenEvent.ACCOUNT_LOGIN_WECHAT);
                IWXAPI mWechatApi = WXAPIFactory.createWXAPI(mContext, Constants.WECHAT_KEY);
                if (mWechatApi.isWXAppInstalled()) {
                    SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";
                    mWechatApi.sendReq(req);
                }
                break;
            case R.id.mine_xiaoxi:
                intent = new Intent(mContext, MessageActivity.class);
                mContext.startActivity(intent);
                break;
            //                        case R.id.mine_wenzhang:
            //                            break;
            case R.id.mine_pinglun:
                intent = new Intent(mContext, MyCommentActivity.class);
                intent.putExtra("my_comment_title", "我的评论");
                mContext.startActivity(intent);
                break;

            case R.id.mine_shoucang:
                if (!Settings.isLoggedIn()) {
                    Utils.showToast("请先登录");
                    Utils.askLogIn((Activity) mContext);
                    return;
                }
                //                if (!Settings.isLoggedIn()) {
                //                    Utils.showToast("请先登录");
                //                    Utils.askLogIn((Activity) mContext);
                //                    return;
                //                }
                UmenEvent.UmengEventMap(mContext, UmenEvent.APP_USERCENTER, UmenEvent.USERCENTER_MYCOLLECT);
                intent = new Intent(mContext, ShouCangActivity.class);
                mContext.startActivity(intent);
                break;
            case R.id.mine_setting:
                UmenEvent.UmengEventMap(mContext, UmenEvent.APP_USERCENTER, UmenEvent.USERCENTER_SETTING);
                intent = new Intent(mContext, SettingActivity.class);
                mContext.startActivity(intent);
                break;
            case R.id.mine_fankui:
                UmenEvent.UmengEventMap(mContext, UmenEvent.APP_USERCENTER, UmenEvent.USERCENTER_SUGGEST);
                MobclickAgent.onEvent(mContext,UmenEvent.USERCENTER_SUGGEST);
                intent = new Intent(mContext, FanKuiActivity.class);
                mContext.startActivity(intent);
                break;
        }
    }

    Oauth2AccessToken mAccessToken;


    //微博回调
    class AuthListener implements WeiboAuthListener {

        @Override
        public void onComplete(Bundle values) {
            // 从 Bundle 中解析 Token
            mAccessToken = Oauth2AccessToken.parseAccessToken(values);
            if (mAccessToken.isSessionValid()) {
                //                Utils.showToast("新浪微博登录成功");
                String token = mAccessToken.getToken();
                String uid = mAccessToken.getUid();
                checkBinQQ(token, uid, Constants.LOGIN_TYPE_SINAID);

            } else {
                // 当您注册的应用程序签名不正确时，就会收到 Code，请确保签名正确
                String code = values.getString("code", "");
            }
        }

        @Override
        public void onCancel() {
        }

        @Override
        public void onWeiboException(WeiboException e) {
        }
    }

    //qq第三方登录要回调的接口
    class listenerQQ implements IUiListener {
        //登录成功调用的方法
        @Override
        public void onComplete(Object o) {
            JSONObject object = (JSONObject) o;
            String token = object.optString("access_token");
            String openId = object.optString("openid");
            Settings.saveQQToken(token);
            Settings.saveQQUid(openId);

            checkBinQQ(token, openId, Constants.LOGIN_TYPE_QQID);
        }

        @Override
        public void onError(UiError uiError) {
        }

        @Override
        public void onCancel() {
        }
    }

    //广播接收者
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, final Intent intent) {
            String action = intent.getAction();
            LogUtil.i("qcl 接收到的广播：", action);
            if (action.equals(Constants.INTENT_USER_LOGGED_IN)) {
                String str = intent.getStringExtra("loginJson");
                Gson gson = new Gson();
                user = gson.fromJson(str, User.class);
                Settings.saveProfile(str);//
                Global.setUser(str); //保存登录信息
                //                Global.user = new Gson().fromJson(Settings.getProfile(), User.class);
                Utils.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        showUi();
                    }
                });
            } else if (action.equals(Constants.INTENT_USER_LOGGED_OUT)) {
                //                Global.user = null;
                //                initView();
                //                bindProfileData();
                Utils.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {

                        hideUi();
                    }
                });
            }

        }
    };


    private void showUi() {
        mineTiShi.setVisibility(View.GONE);
        mineNoDengLu.setVisibility(View.GONE);
        mineOK.setVisibility(View.VISIBLE);
        mineXiaoxi.setVisibility(View.GONE);
        //                        mineWenzhang.setVisibility(View.VISIBLE);
        minePinglun.setVisibility(View.VISIBLE);
        layout_shoucang.setVisibility(View.VISIBLE);
        name.setText(user.nickname);
        view_line.setVisibility(View.VISIBLE);
        jianjie.setText(user.introduction);
        // 显示图片要用Image-Loader-master这个第三方类库
        ImageLoader.getInstance().displayImage(
                user.avatar + Constants.IMAGE_WEBP, mineOkTouXiang,
                ImageLoaderOptions.options);
        if (user.unread_message > 0) {
            hongdian.setVisibility(View.VISIBLE);
        } else {
            hongdian.setVisibility(View.GONE);
        }
        if (user.user_type > 0) {
            dengji.setVisibility(View.VISIBLE);
        } else {
            dengji.setVisibility(View.GONE);
        }
    }

    private void hideUi() {
        mineTiShi.setVisibility(View.VISIBLE);
        mineNoDengLu.setVisibility(View.VISIBLE);
        mineOK.setVisibility(View.GONE);
        view_line.setVisibility(View.GONE);
        mineXiaoxi.setVisibility(View.GONE);
        layout_shoucang.setVisibility(View.GONE);
        //                        mineWenzhang.setVisibility(View.GONE);
        minePinglun.setVisibility(View.GONE);
    }

}
